package com.pignest.hotel.schedule;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.pignest.hotel.beans.Dictionary;
import com.pignest.hotel.service.AuditService;
import com.pignest.hotel.service.DictionaryService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Config;
import com.pignest.hotel.system.Key;
import com.pignest.hotel.system.L;
import com.pignest.hotel.util.DateUtil;

/**
 * 夜审任务
 * */
public class NightAuditJob implements Job {
	
	private static final Object LOCK = new Object();

	/**
	 * 夜审
	 * */
	public void audit() {
		L.log(L.Action.START, "夜审");
		synchronized (LOCK) {
			final AuditService service = Services.getAuditServcie();
			DictionaryService dictionaryService = Services.getDictionaryService();
			Dictionary lastAudtiTime = dictionaryService.getDictionaryByKey(Key.LAST_AUDIT_TIME);
			Date time = lastAudtiTime == null ? null : DateUtil.toDate(lastAudtiTime.getValue());
			if (time != null) {
				int h = Config.getMinNightAuditInterval();
				if (System.currentTimeMillis() - time.getTime() < h * DateUtil.ONE_HOUR)
					return;
			}
			service.executeInTransaction(new Runnable() {
				@Override
				public void run() {
					//夜审工作1: 自动产生房费
					service.execCalculateCurrentAccounts();
					//夜审工作2: 更改房间状态(空干净->空隔夜, 在住->在住脏)
					Services.getRoomService().updateUseStatus();
				}
			});
			if (lastAudtiTime == null) {
				lastAudtiTime = new Dictionary();
				lastAudtiTime.setKey(Key.LAST_AUDIT_TIME);
			}
			lastAudtiTime.setValue(DateUtil.toString(System.currentTimeMillis()));
			dictionaryService.insertOrUpdate(lastAudtiTime);
		}
		L.log(L.Action.STOP, "夜审");
	}

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		if (!Config.isManualNightAudit()) {
			audit();
		}
	}
	
}
